/**
* Accenture LLP
* Trigger : UpdateQuotaId
* Object: Opportunity_Split__c
* Description : This Trigger is used to populte Quota Id on Opportunity Split record.
*
*/

trigger OORTelesalesUpdateQuotaId on Opportunity_Split__c (Before Insert, Before Update) {


   List<Opportunity_Split__c> newRecords = Trigger.New;
    
        
   if(trigger.isInsert){     
    
      for(Opportunity_Split__c splitRec : newRecords){
             if(splitRec.Booked_Date__c!=NULL ){
              Integer bookDateYear = splitRec.Booked_Date__c.Year();
              Integer bookDateMonth = splitRec.Booked_Date__c.Month();
              
              // Loop for to retrive record from  Quota Management object based on MC  &  Quote date to update the Quota Id on Opportunity Split.
               For ( QuotaManagement__c quotaId : [select os.Id from QuotaManagement__c os where (CALENDAR_YEAR(os.QuotaDate__c)=: bookDateYear and CALENDAR_MONTH(os.QuotaDate__c)=: bookDateMonth )and os.MC__c=:splitRec.Owner_ID__c ]){
                     
                     splitRec.QuotaManagement__c= quotaId.id;
                     
               }                    
           }
        }      
    }
    
    if(trigger.isUpdate){ 
    
         for(Opportunity_Split__c splitRec : newRecords){
             
             // Check book order date or Split oner is changed
             
             If(splitRec.Booked_Date__c != NULL && (Trigger.OldMap.get(splitRec.id).Booked_Date__c != splitRec.Booked_Date__c || (splitRec.Owner_ID__c !=Trigger.OldMap.get(splitRec.id).Owner_ID__c))){
             Integer bookDateYear = splitRec.Booked_Date__c.Year();
              Integer bookDateMonth = splitRec.Booked_Date__c.Month();
               // Loop for to retrive record from  Quota Management object based on MC  &  Quote date to update the Quota Id on Opportunity Split.              
               For ( QuotaManagement__c quotaId : [select os.Id from QuotaManagement__c os where (CALENDAR_YEAR(os.QuotaDate__c)=: bookDateYear and CALENDAR_MONTH(os.QuotaDate__c)=: bookDateMonth )and os.MC__c=:splitRec.Owner_ID__c ]){
                     
                     splitRec.QuotaManagement__c= quotaId.id;
                     
               }  
             }                  
           }
    
    }

}